package com.zp.self.module.level_1_问道.III_多线程;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ：by Zeng Peng
 * @date ：Created 2022/7/29 8:01
 * @description ：
 */
public class VolatileTest {
    volatile int i=0;
    @Test
    public void test() throws InterruptedException {
        CountDownLatch countStart = new CountDownLatch(1);
        CountDownLatch countEnd = new CountDownLatch(2);
        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute(()->{
            try {
                countStart.await();
                for (int j = 0; j < 10000; j++)
                    i++;
            } catch (InterruptedException ignored) {}
            countEnd.countDown();
        });
        executor.execute(()->{
            try {
                countStart.await();
                for (int j = 0; j < 10000; j++)
                    i++;
            } catch (InterruptedException ignored) {}
            countEnd.countDown();
        });
        countStart.countDown();//线程同时被唤醒，同时执行
        countEnd.await();//等待执行结束
        executor.shutdown();
        System.out.println("两个线程分别累加10000次后的结果："+i);//两个线程分别累加10000次后的结果：11227
    }
}
